<template>
  <div class="app-container">
    <h1 class="title">添加管理角色</h1>
    <el-button type="primary" icon="el-icon-plus" @click="handleAddRole">新建角色</el-button>
    <h1 class="title">搜索管理角色</h1>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="角色名称">
        <el-input v-model="formInline.id" placeholder="角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
        <el-button type="primary" @click="onSearch" icon="el-icon-search" >搜索</el-button>
        </el-form-item>
    </el-form>
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border v-loading="tableloading">
      <el-table-column align="center" label="角色" width="220">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column> 
      <el-table-column align="center" label="角色描述" width="220">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新建角色'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色">
          <el-input v-model="role.name" placeholder="输入角色名称" clearable/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input  v-model="role.description" placeholder="输入描述文字" clearable/>
        </el-form-item>
        <el-form-item label="角色权限选项">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            :default-expanded-keys='role.resourceIds'
            :default-checked-keys="role.resourceIds"
            node-key="resourceId"
            class="permission-tree"
            @check="handleCheckChange"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="cancelRole">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenusList,addRole,getRoleList,deleteRole,getRoutes,getRoleDetail ,updateRole} from "@/api";
import md5 from 'js-md5';
const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  inject: ['reload'],
  data() {
    return {
      tableloading : false,
      formInline: {
        id: '',
      },
      role: {
        roleId : '',
        name : '',
        description : '',
        resourceIds : []
      },
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'resourceName'
      },
      routesData : ''
    }
  },

  created() {
    this.getMenusList();
    this.getRoleList();
  },
  methods: {
    handleCheckChange(data, checked, indeterminate) {
      // let getNodes = checked;
       let getNodes = this.$refs.tree.getCheckedNodes();
      let resourceIds = [];
      let resourceIds1 ;
      let resourceIds2 ;
          for (let index = 0; index < getNodes.length; index++) {
            let element = getNodes[index].resourceId;
                resourceIds.push(element);
          }
          this.role.resourceIds = resourceIds;
    },
    ///////搜索
    onSearch(){
        this.getRoleList();
    },
    ////获取角色列表
    getRoleList() {
      this.tableloading = true;
      let formData = {
        start : 0,
        length : 10,
        search : this.formInline.id
      }
      getRoleList(formData).then(response => {
        if (response.data) {
            this.rolesList = response.data;
            this.tableloading = false;
        } else {
          this.tableloading = false;
          this.$message.error(response.message);
        }
        
      }, response => {

      });

    },
     ////获取新建角色菜单权限选项列表
    getMenusList() {
      let formData = {}
      getMenusList(formData).then(response => {
        if ('0' == response.code) {
        let  element = response.data;              
            this.routesData = element;
        } else {
          this.$message.error(response.message);
        }
        
      }, response => {

      });
    },
     ////获取菜单列表
    // getRoutes() {
    //   let formData = {
    //     userName : sessionStorage.getItem('userInfo'),
    //   }
    //   getRoutes(formData).then(response => {
    //     if ('0' == response.code) {
    //         this.menuList = response.data;
    //         if(response.data.length == 0){
    //             this.$router.push("/home");
    //         }
    //     } else {
    //       this.$message.error(response.msg);
    //     }

    //   }, response => {

    //   });

    // },
     ////添加角色
    addRoles() {
      let formData = {
        roleName : this.role.name,
        description : this.role.description,
        resourceIds : this.role.resourceIds
      }
      addRole(formData).then(response => {
        if ('0' == response.code) {
          this.getRoleList();
          this.role.name ='';
          this.role.description = '';
          this.role.resourceIds = [];
        } else {
          this.$message.error(response.message);
        }
      }, response => {

      });
    },
    ////获取编辑角色详情
    getRoleDetail(roleId){
      let formData = {
        roleId : roleId,
      }
      var rolesChildrenListId = [];
      // var rolesId = [];
      getRoleDetail(formData).then(response => {
        if ('0' == response.code) {
          this.role.roleId = response.data.roleId;
          this.role.name = response.data.roleName;
          this.role.description = response.data.description;
          this.role.resourceIds = response.data.list;

          for (var index = 0; index < response.data.list.length; index++) {
                rolesChildrenListId.push(response.data.list[index].resourceId);
            for (var j = 0; j < response.data.list[index].children.length; j++) {
                rolesChildrenListId.push(response.data.list[index].children[j].resourceId);  
                console.log(rolesChildrenListId)    
            }
          }  
          this.role.resourceIds = rolesChildrenListId;
        } else {
          this.$message.error("response.msg");
        }
      }, response => {

      });
    },
     ////删除角色
    deleteRole(roleId) {
      let formData = {
        roleId : roleId,
      }
      deleteRole(formData).then(response => {
        if ('0' == response.code) {
            this.getRoleList();
        } else {
          this.$message.error(response.message);
        }
      }, response => {

      });
    },
    /////编辑角色
    updataRoles(){
      let formData = {
        roleId : this.role.roleId ,
        roleName : this.role.name ,
        description :  this.role.description ,
        resourceIds :  this.role.resourceIds 
      }
      updateRole(formData).then(response => {
        if ('0' == response.code) {
            this.getRoleList();
            this.getRoleDetail(this.role.roleId);
        } else {
          this.$message.error(response.message);
        }
      }, response => {

      });
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    ////新建角色按钮
    handleAddRole() {
      // this.role = Object.assign({}, defaultRole)
      // if (this.$refs.tree) {
      //   this.$refs.tree.setCheckedNodes([])
      // }
      
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      // this.role = deepClone(scope.row)
      this.$nextTick(() => {
        this.getRoleDetail(scope.row.roleId);
      //   const routes = this.generateRoutes(this.role.routes)
        // this.$refs.tree.setCheckedNodes(this.generateArr(routes))
        // set checked state of a node not affects its father and child nodes
        
        this.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定要删除吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.deleteRole(row.roleId);
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除!'
          })
        })
        .catch(err => { console.error(err) })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    cancelRole(){
       this.dialogVisible = false;
       this.reload();
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      // const checkedKeys = this.$refs.tree.getCheckedKeys()
      // this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)

      if (isEdit) {
        // await updateRole(this.role.key, this.role)
        // for (let index = 0; index < this.rolesList.length; index++) {
        //   if (this.rolesList[index].key === this.role.key) {
        //     this.rolesList.splice(index, 1, Object.assign({}, this.role))
        //     break
        //   }
        // }
        this.updataRoles();
      } else {
        this.addRoles();
        // const { data } = await addRole(this.role)
        // this.role.key = data.key
        // this.rolesList.push(this.role)
      }
      this.reload();
      // const { description, key, name } = this.role
      this.dialogVisible = false
      this.$notify({
        title: '成功',
        dangerouslyUseHTMLString: true,
        // message: `
        //     <div>Role Key: ${key}</div>
        //     <div>Role Name: ${name}</div>
        //     <div>Description: ${description}</div>
        //   `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
    .title{
      font-weight: bold;
      color: #9e9e9e;
      padding: 10px 0;
      margin: 20px 0 40px 0;
      border-bottom: 1px solid #E0E0E0;
    }
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
